package ciyuan.Network;

import ciyuan.Gui.ContainerRegistry;
import ciyuan.Gui.Ornaments.OrnamentsContainer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkHooks;

import javax.annotation.Nullable;
import java.util.function.Supplier;

public class ContainerOpenPacket {

    private final String guiType;

    public ContainerOpenPacket(PacketBuffer buffer) {
        guiType = buffer.readUtf();
    }

    public ContainerOpenPacket(String guiType) {
        this.guiType = guiType;
    }

    public void toBytes(PacketBuffer buf) {
        buf.writeUtf(guiType);
    }

    public void handler(Supplier<NetworkEvent.Context> ctx) {
        if (ctx.get().getDirection().getOriginationSide().isClient()) {
            ctx.get().enqueueWork(() -> {
                if ("OrnamentsScreen".equals(guiType)) {
                    NetworkHooks.openGui(ctx.get().getSender(), new INamedContainerProvider() {
                        @Override
                        public ITextComponent getDisplayName() {
                            return new TranslationTextComponent("ciyuan.container.dsc14");
                        }

                        @Nullable
                        @Override
                        public Container createMenu(int id, PlayerInventory playerInventory, PlayerEntity player) {
                            return new OrnamentsContainer(ContainerRegistry.ornamentsContainer.get(), id, playerInventory);
                        }
                    });
                }
            });
        }
        ctx.get().setPacketHandled(true);
    }

}
